package com.bw.mine.login.viewmodel

import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ToastUtils
import com.bw.lib_base.base.BaseViewModel
import com.bw.mine.login.entiity.LoginEntity
import com.hyphenate.chat.EMClient
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(val loginRepo: LoginRepo) : BaseViewModel() {
    private val _loginData = MutableStateFlow<LoginEntity?>(null)
    val loginData : StateFlow<LoginEntity?> = _loginData

    fun getLogin(password:String,username:String){
        viewModelScope.launch {
            Log.d("getLogin", "getLogin: 执行了")
            if (isInitLife()){
                try {
                    Log.d("getLogin", "生命周期？: 执行了")
                    lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                        val login = loginRepo.getLogin(password, username)
                        Log.d("gggg", "getLogin: 你还")
                        _loginData.emit(login)
                    }
                }catch (e:Exception){
                    EMClient.getInstance().logout(true);

                    ToastUtils.showLong("登录失败")
                }
            }
        }
    }

    fun getRequest(password:String,username:String){
        viewModelScope.launch {
            Log.d("getRequest", "getLogin: 执行了")
            if (isInitLife()){
                Log.d("getRequest", "生命周期？: 执行了")
                try {
                    lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                        val login = loginRepo.getRequest(password, username)
                        _loginData.value = login
                    }
                }catch (e:Exception){
                    ToastUtils.showLong("注册失败")
                }
            }
        }
    }
}